//导入 axios
import axios from 'axios';
import swal from 'sweetalert';
//获取按钮
let btn = document.querySelector('button[type=submit]');

//获取表单元素
let form = document.querySelector('form');
//获取 token
let token = localStorage.getItem('token');
if(!token){
  location.href = '/login.html';
}
btn.onclick = async function(e){
  //阻止默认行为
  e.preventDefault();
  //获取表单数据, 
  let formdata = new FormData(form);
  //将 formdata 数据转为 querystring
  const queryString = new URLSearchParams(formdata).toString();
  //发送 AJAX 请求
  let result = await axios.post('http://127.0.0.1:3001/api/account', queryString, {
    headers: {
      token: token
    }
  });
  //判断
  if(result.data.code==='0000'){
    //登录成功之后, 跳转账单的列表页
    swal({
      title: "温馨提示",
      text: "新增成功",
      icon: "success",
      buttons: true,
      dangerMode: false,
    }).then(() => {
      //跳转
      location.href = '/accounts.html';
    })
  }else{
    swal({
      title: "温馨提示",
      text: "新增失败",
      icon: "error",
      dangerMode: true,
    })
  }
}